package com.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.entity.SysPermission;
import com.rbac.mapper.SysPermissionMapper;
import com.rbac.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 权限服务实现类
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@Service
@Transactional
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Override
    public IPage<SysPermission> page(IPage<SysPermission> page, String permissionName, String permissionCode, Integer resourceType, Integer status) {
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(permissionName), SysPermission::getPermissionName, permissionName)
               .like(StringUtils.hasText(permissionCode), SysPermission::getPermissionCode, permissionCode)
               .eq(resourceType != null, SysPermission::getResourceType, resourceType)
               .eq(status != null, SysPermission::getStatus, status)
               .orderByAsc(SysPermission::getSortOrder)
               .orderByDesc(SysPermission::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public List<SysPermission> getPermissionTree() {
        return baseMapper.selectPermissionTree();
    }

    @Override
    public List<SysPermission> getPermissionsByRoleId(Long roleId) {
        return baseMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public boolean existsByPermissionCode(String permissionCode) {
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getPermissionCode, permissionCode);
        return count(wrapper) > 0;
    }

    @Override
    public boolean existsByPermissionCodeAndIdNot(String permissionCode, Long id) {
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getPermissionCode, permissionCode)
               .ne(SysPermission::getId, id);
        return count(wrapper) > 0;
    }
}
